package Algorithm.LengthOfLongestSubstring;

public class LengthOfLongestSubstring2 {
    public static int  lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) return 0;
        char[] chs = s.toCharArray();
        int[] freq = new int[256];
        int L = 0, R = -1;
        int res = 0;
        while (R < s.length()) {
            if (R + 1 == s.length()) //一定要break, 一是防止越界，二是不然L不会break； R你都到str.length - 1，L你要再移动也不会更长了
                break;
            //如果freq[chs[R + 1]] != 0，就要先一直移动L,直到freq[chs[R+1]]可以进入窗口，这个过程不会错过最优解
            if (freq[chs[R + 1]] == 0)
                freq[chs[++R]]++;
            else
                freq[chs[L++]]--;
            res = Math.max(res, R - L + 1);
        }
        return res;
    }


    public static void main(String[] args) {

        String a = "abcabcbb";
        char[] chars = a.toCharArray();
        int[] freq = new int[256];
        int R = -1;
        System.out.println("chars[R + 1]    "+chars[R + 1]);
        System.out.println("freq[chars[R + 1]]    "+freq[chars[R + 1]]);
        int i = lengthOfLongestSubstring(a);
        System.out.println(i);
    }
}
